
using AutoMapper;
using Coldairarrow.Util;
using DTO;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Model;
using Newtonsoft.Json;
using NPOI.SS.Formula.Functions;
using RestSharp;
using SqlSugar;
using System.Net;
using Util;

namespace API.Controllers
{
    public class FoodProcureController : BaseController
    {
        Repository<tFoodProcure> _FoodProcure;
        Repository<tCanteenMenu> _tCanteenMenu; 
        Repository<tMealReporting> _repMeal; 
        Repository<tSignIn> _tSignIn;
        Repository<tFoodResidue> _foodResidue;
        readonly IMapper _mapper;
        ISqlSugarClient _db;
        readonly object _lock = new object();
        public FoodProcureController(Repository<tFoodProcure> FoodProcure, IMapper mapper, ISqlSugarClient db, Repository<tCanteenMenu> tCanteenMenu, Repository<tMealReporting> repMeal, Repository<tSignIn> tSignIn, Repository<tFoodResidue> foodResidue)
        {
            _FoodProcure = FoodProcure;
            _mapper = mapper;
            _db = db;
            _tCanteenMenu = tCanteenMenu;
            _repMeal = repMeal;
            _tSignIn = tSignIn;
            _foodResidue = foodResidue;
        }
        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResultMsg<string>> Save([FromBody] SaveFoodProcureInput dto)
        {
            ResultMsg<string> result = new ResultMsg<string>();
            try
            {
                var model = _mapper.Map<tFoodProcure>(dto);
                InitEntity(model);
                await _FoodProcure.InsertOrUpdateAsync(model);
                return result.Success();
            }
            catch (Exception ex)
            {
                Util.NLOG.LogHelper.Error("FoodProcureController--Save:" + ex.ToString());
                return result.Error(ex.ToString());
            }
        }

        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResultMsg<List<FoodProcureOutput>>> GetList([FromBody] FoodProcureListInput dto)
        {
            ResultMsg<List<FoodProcureOutput>> result = new ResultMsg<List<FoodProcureOutput>>();
            try
            {
                if (dto.PageNum <= 0)
                {
                    return result.Error("PageNum不能小于或等于0");
                }
                if (dto.PageSize <= 0)
                {
                    return result.Error("PageSize不能小于或等于0");
                }
                SqlSugar.PageModel pageModel = new SqlSugar.PageModel
                {
                    PageIndex = dto.PageNum,
                    PageSize = dto.PageSize,
                };
                var exp = Expressionable.Create<tFoodProcure>();
                if (!string.IsNullOrWhiteSpace(dto.Name))
                {
                    exp.And(x => x.FName.Contains(dto.Name));
                }
                var list = (await _FoodProcure.GetPageListAsync(exp.ToExpression(), pageModel)).OrderByDescending(x => x.CreateTime).ToList();
                var FoodProcureOutputs = _mapper.Map<List<FoodProcureOutput>>(list);
                return result.Success(FoodProcureOutputs, pageModel.TotalCount);
            }
            catch (Exception ex)
            {
                Util.NLOG.LogHelper.Error("FoodProcureController--GetList:" + ex.ToString());
                return result.Error(ex.ToString());
            }
        }
        /// <summary>
        /// 获取唯一
        /// </summary>
        /// <param name="id">主键ID</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ResultMsg<FoodProcureOutput>> GetTheOne(string id)
        {
            ResultMsg<FoodProcureOutput> result = new ResultMsg<FoodProcureOutput>();
            try
            {
                var model = await _FoodProcure.GetByIdAsync(id);
                var dao = _mapper.Map<FoodProcureOutput>(model);
                return result.Success(dao);
            }
            catch (Exception ex)
            {
                Util.NLOG.LogHelper.Error("FoodProcureController--GetTheOne:" + ex.ToString());
                return result.Error(ex.ToString());
            }
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id">主键ID</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ResultMsg<string>> Del(string id)
        {
            ResultMsg<string> result = new ResultMsg<string>();
            try
            {
                await _FoodProcure.DeleteByIdAsync(id);
                return result.Success();
            }
            catch (Exception ex)
            {
                Util.NLOG.LogHelper.Error("FoodProcureController--Del:" + ex.ToString());
                return result.Error(ex.ToString());
            }
        }

        /// <summary>
        /// 食堂触摸屏获取实时就餐人数
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost]
        public ResultMsg<GetFoodResidueOutput1> GetFoodResidue()
        {
            ResultMsg<GetFoodResidueOutput1> result = new ResultMsg<GetFoodResidueOutput1>();
            try
            {
                GetFoodResidueOutput1 dao = new GetFoodResidueOutput1();


                Common commonInstance = new Common(_db); // 使用db实例化Common类
                var lunch_start = commonInstance.GetConfig().LunchStartScan;
                var lunch_end = commonInstance.GetConfig().LunchEndScan;
                var dinner_start = commonInstance.GetConfig().DinnerStartScan;
                var dinner_end = commonInstance.GetConfig().DinnerEndScan;

                DateTime dt = DateTime.Now;
                DateTime d1 = new DateTime(dt.Year, dt.Month, dt.Day, int.Parse(lunch_start.Split(':')[0]), int.Parse(lunch_start.Split(':')[1]), 0);
                DateTime d2 = new DateTime(dt.Year, dt.Month, dt.Day, int.Parse(lunch_end.Split(':')[0]), int.Parse(lunch_end.Split(':')[1]), 0);
                DateTime d3 = new DateTime(dt.Year, dt.Month, dt.Day, int.Parse(dinner_start.Split(':')[0]), int.Parse(dinner_start.Split(':')[1]), 0);
                DateTime d4 = new DateTime(dt.Year, dt.Month, dt.Day, int.Parse(dinner_end.Split(':')[0]), int.Parse(dinner_end.Split(':')[1]), 0);
                //判断是中午签到还是晚上签到
                int meenType = 0;
                if (dt <= d2)
                {
                    meenType = 1;
                }
                else if (dt > d2)
                {
                    meenType = 2;
                }
                var model = _tCanteenMenu.GetFirst(x => x.FMTime == DateTime.Now.Date && x.FMType == meenType);
                if (model != null)
                {
                    dao.meen = model.FMName;
                    dao.meen2 = model.FMName2;
                    dao.meen3 = model.FMName3;
                    dao.meen4 = model.FSoup;
                }
                dao.allReport = _repMeal.Count(x => x.FRTime == dt.Date && x.FMType == meenType && !x.FDeleted);
                DateTime start = new DateTime();
                DateTime end = new DateTime();
                if (meenType == 1)
                {
                    start = d1;
                    end = d2;
                }
                else
                {
                    start = d3;
                    end = d4;
                }
                dao.currentEat = _tSignIn.Count(x => x.CreateTime >= start && x.CreateTime < end);
                var oddModel = _foodResidue.GetFirst(x => x.CreateTime >= start && x.CreateTime < end);
                dao.odd = oddModel == null ? 0 : oddModel.FRealresidue;
                dao.IsSendOdd = dao.odd == 0 ? false : true;

                dao.residue = dao.allReport - dao.currentEat + dao.odd;

                return result.Success(dao);
            }
            catch (Exception ex)
            {
                Util.NLOG.LogHelper.Error("tFoodResidueController-GetFoodResidue:" + ex);
                return result.Exception();
            }
        }
        /// <summary>
        /// 发布剩余份量
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost]
        public ResultMsg<string> ReleaseFoodResidue(ReleaseFoodResidueInput input)
        {
            ResultMsg<string> result = new ResultMsg<string>();
            try
            {
                //数据库进行存在更改，没有插入操作
                DateTime dt = DateTime.Now;
                tFoodResidue model = new tFoodResidue();
                if (dt.Hour >= 8 && dt.Hour < 14)
                {
                    model = _foodResidue.GetFirst(x => x.CreateTime >= DateTime.Parse(dt.Date.ToString("yyyy-MM-dd") + " 7:00:00") && x.CreateTime < DateTime.Parse(dt.Date + " 14:00:00"));
                }
                else if (dt.Hour >= 14 && dt.Hour < 22)
                {
                    model = _foodResidue.GetFirst(x => x.CreateTime >= DateTime.Parse(dt.Date.ToString("yyyy-MM-dd") + " 14:00:00") && x.CreateTime <= DateTime.Parse(dt.Date + " 21:00:00"));
                }

                if (model == null)
                {
                    _foodResidue.Insert(new tFoodResidue
                    {
                        FResidue = input.Count,
                        FRealresidue = input.Count,
                        CreatorId = "Admin",
                        CreateTime = DateTime.Now,
                        Id=IdHelper.GetId()
                    });
                }
                //往小程序发布模版信息

                //var response = RequestHelper.HttpGet(string.Format("https://app.yingdl.com:9527/Wechat/SendMsgToOne?userid={0}&userName={1}&content=晚餐剩余{2}份,快来吃饭呀&first={3}&remark={4}&path={5}", 587,"饭堂阿姨",input.Count,"","","pages/cantmeen/odd"));


                var client = new RestClient("https://app.yingdl.com:9527/Wechat/SendMsgToAllUser");
                var request = new RestRequest("", RestSharp.Method.Get);
                request.AddParameter("userName", "饭堂阿姨");
                request.AddParameter("content", string.Format("晚餐还余{0}份,快来吃饭呀", input.Count));
                request.AddParameter("first", "");
                request.AddParameter("remark", "");
                request.AddParameter("path", "pages/cantmeen/odd");
                var response = client.Execute(request);

                object ret = null;
                if (response.StatusCode == HttpStatusCode.OK)
                {
                    if (response != null && response.Content != null)
                    {
                        ret = JsonConvert.DeserializeObject(response.Content);
                    }
                }
                else if (response.StatusCode == HttpStatusCode.NotFound)
                {
                    ret = "资源不存在";
                }
                else if (response.StatusCode == HttpStatusCode.BadRequest)
                {
                    ret = "请求不合法";
                }
                return result.Success("");
            }
            catch (Exception ex)
            {
                Util.NLOG.LogHelper.Error("tFoodResidueController-ReleaseFoodResidue:" + ex);
                return result.Exception();
            }
        }

        /// <summary>
        /// 报余餐
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost]
        public ResultMsg<string> ReportFoodResidue(ReportFoodResidueInput input)
        {
            ResultMsg<string> result = new ResultMsg<string>();
            try
            {
                DateTime dt = DateTime.Now;
                DateTime start = new DateTime();
                DateTime end = new DateTime();
                int mType = 0;
                if (dt.Hour >= 8 && dt.Hour < 14)
                {
                    mType = 1;
                    start = DateTime.Parse(dt.Date.ToString("yyyy-MM-dd") + " 7:00:00");
                    end = DateTime.Parse(dt.Date.ToString("yyyy-MM-dd") + " 14:00:00");
                }
                else if (dt.Hour >= 14 && dt.Hour < 22)
                {
                    mType = 2;
                    start = DateTime.Parse(dt.Date.ToString("yyyy-MM-dd") + " 14:00:00");
                    end = DateTime.Parse(dt.Date.ToString("yyyy-MM-dd") + " 21:00:00");
                }
                var model = _foodResidue.GetSingle(x => x.CreateTime >= start && x.CreateTime < end);
                lock (_lock)
                {
                    if (model.FRealresidue <= 0)
                    {
                        return result.Success("不好意思哦，已经没有餐了");
                    }
                    else
                    {

                        var repModel = _repMeal.GetFirst(x => x.CreateTime >= start && x.CreateTime < end && x.FEID == input.userId && x.FMType == mType && !x.FDeleted);
                        if (repModel == null)
                        {
                            _repMeal.Insert(new tMealReporting
                            {
                                FMType = mType,
                                FEID = input.userId,
                                FEName = input.userName,
                                FRTime = DateTime.Now.Date,
                                FDeptName = "",
                                FDeleted = false,
                                FWorkOver = false,
                                FCancellation = false,
                                FCancelReason = string.Empty,
                                FCancelTime = DateTime.MinValue,
                                FIsOdd = true,
                                Id = IdHelper.GetId(),
                            });
                            model.FRealresidue--;
                            _foodResidue.Update(model);
                        }
                        return result.Success("成功报餐!");
                    }
                }

            }
            catch (Exception ex)
            {
                Util.NLOG.LogHelper.Error("tFoodResidueController-ReleaseFoodResidue:" + ex);
                return result.Exception();
            }
        }
        /// <summary>
        /// 小程序端获取报余餐相关信息
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost]
        public ResultMsg<GetFoodResidueOutput1> GetFoodResidueByMini(FoodResidueByMiniInput input)
        {
            ResultMsg<GetFoodResidueOutput1> result = new ResultMsg<GetFoodResidueOutput1>();
            try
            {
                GetFoodResidueOutput1 dao = new GetFoodResidueOutput1();
                DateTime dt = DateTime.Now;
                int meenType = 0;
                if (dt.Hour >= 8 && dt.Hour < 14)
                    meenType = 1;
                else if (dt.Hour >= 14 && dt.Hour < 22)
                {
                    meenType = 2;
                }
                var model = _tCanteenMenu.GetFirst(x => x.FMTime == DateTime.Now.Date && x.FMType == meenType);
                if (model != null)
                {
                    dao.meen = model.FMName;
                    dao.meen2 = model.FMName2;
                    dao.meen3 = model.FMName3;
                    dao.meen4 = model.FSoup;
                }
                dao.allReport = _repMeal.Count(x => x.FRTime == dt.Date && x.FMType == meenType && !x.FDeleted && !x.FIsOdd);
                DateTime start = new DateTime();
                DateTime end = new DateTime();
                if (meenType == 1)
                {
                    start = DateTime.Parse(dt.Date.ToString("yyyy-MM-dd") + " 7:00:00");
                    end = DateTime.Parse(dt.Date.ToString("yyyy-MM-dd") + " 14:00:00");
                }
                else
                {
                    start = DateTime.Parse(dt.Date.ToString("yyyy-MM-dd") + " 14:00:00");
                    end = DateTime.Parse(dt.Date.ToString("yyyy-MM-dd") + " 21:00:00");
                }
                dao.currentEat = _tSignIn.Count(x => x.CreateTime >= start && x.CreateTime < end);
                var oddModel = _foodResidue.GetFirst(x => x.CreateTime >= start && x.CreateTime < end);
                dao.odd = oddModel == null ? 0 : oddModel.FRealresidue;
                dao.IsSendOdd = dao.odd == 0 ? false : true;

                dao.residue = dao.allReport - dao.currentEat + dao.odd;
                dao.Report = _repMeal.Count(x => x.FEID == input.userId && x.FEName == input.userName && x.FMType == meenType && x.FRTime == DateTime.Now.Date && !x.FDeleted) > 0 ? true : false;

                return result.Success(dao);
            }
            catch (Exception ex)
            {
                Util.NLOG.LogHelper.Error("tFoodResidueController-GetFoodResidueByMini:" + ex);
                return result.Exception();
            }
        }
    }
}
